import 'package:chain/box.dart';
import 'package:chain/model/game_level.dart';
import 'package:chain/model/game_status.dart';
import 'package:chain/model/node.dart';
import 'package:chain/veiwmodel.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(ChangeNotifierProvider(
    create: (_) => GameViewModel(),
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        fontFamily: 'xiaofang',
      ),
      home: const Index(),
    ),
  ));
}

class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: const BoxDecoration(
          color: Colors.white,
          image: DecorationImage(
            image: AssetImage('assets/bg.png'),
            fit: BoxFit.contain,
            repeat: ImageRepeat.repeatY,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              '数字连消',
              style: TextStyle(
                color: Colors.black,
                fontSize: 50,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 40),
            InkWell(
              onTap: () {
                Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(builder: (context) => MyGame()),
                    (route) => route == null);
              },
              child: Container(
                width: 200,
                height: 70,
                decoration: const BoxDecoration(
                  color: Colors.amber,
                ),
                child: const Center(
                  child: Text(
                    '开始游戏',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 25,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MyGame extends StatefulWidget {
  const MyGame({Key? key}) : super(key: key);

  @override
  State<MyGame> createState() => _MyGameState();
}

class _MyGameState extends State<MyGame> {
  GameViewModel? gameViewModel;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
    if (this.gameViewModel != gameViewModel) {
      this.gameViewModel = gameViewModel;

      GameLevel gameLevel =
          GameLevel(level: 1, containerSize: MediaQuery.of(context).size);
      gameViewModel.startLevel(gameLevel, true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Color.fromARGB(255, 72, 77, 136),
        leading: TextButton(
          onPressed: () {
            Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(builder: (context) => Index()),
                (route) => route == null);
          },
          child: const Icon(
            Icons.home,
            color: Colors.white,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () =>
                Provider.of<GameViewModel>(context, listen: false).restart(),
            child: const Icon(
              Icons.refresh,
              color: Colors.white,
            ),
          ),
        ],
      ),
      body: Center(
        child: Selector<GameViewModel, bool>(
          selector: (context, viewModel) => viewModel.gameStatus.gameOver,
          builder: (BuildContext context, gameOver, Widget? child) {
            return Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              decoration: const BoxDecoration(
                // color: gameOver
                //     ? Color.fromARGB(255, 255, 109, 109)
                //     : Color.fromARGB(255, 114, 234, 255),
                image: DecorationImage(
                  image: AssetImage('assets/bgg.jpg'),
                  fit: BoxFit.fill,
                ),
              ),
              child: child!,
            );
          },
          child: GestureDetector(
            onPanUpdate: (updateDetail) {
              Provider.of<GameViewModel>(context, listen: false)
                  .updatePointer(updateDetail.localPosition);
            },
            onPanEnd: (_) {
              Provider.of<GameViewModel>(context, listen: false)
                ..updatePointer(null)
                ..endPointer();
            },
            child: Selector<GameViewModel, List<Node>>(
              selector: (context, viewModel) =>
                  viewModel.allNode.values.toList(),
              builder: (BuildContext context, allNode, Widget? child) {
                return Stack(
                  children: [
                    ...allNode.map(
                      (e) => Box(
                        e,
                        key: ValueKey(e.id),
                      ),
                    ),
                    Selector<GameViewModel, bool>(
                      selector: (context, viewModel) =>
                          viewModel.gameStatus.gameOver,
                      builder: (BuildContext context, gameOver, Widget? child) {
                        return gameOver
                            ? const Align(
                                alignment: AlignmentDirectional.center,
                                child: Text(
                                  "游戏结束",
                                  style: TextStyle(fontSize: 30),
                                ),
                              )
                            : const SizedBox();
                      },
                    ),
                    child!,
                  ],
                );
              },
              child: Align(
                alignment: AlignmentDirectional.topCenter,
                child: Container(
                  padding: const EdgeInsets.all(8.0),
                  color: Color.fromARGB(255, 250, 200, 124),
                  child: Selector<GameViewModel, GameStatus>(
                    selector: (context, viewModel) => viewModel.gameStatus,
                    builder: (BuildContext context, gameStatus, Widget? child) {
                      return Row(
                        children: [
                          Text(
                            "当前等级: ${gameStatus.level?.level}",
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 21, 21, 21)),
                          ),
                          const SizedBox.square(dimension: 10),
                          Text(
                            "最大方块: ${gameStatus.curMaxValue}",
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 53, 53, 53)),
                          ),
                          const SizedBox.square(dimension: 10),
                          Text(
                            "最多方块数: ${gameStatus.level?.nextLevelValue}",
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 48, 48, 48)),
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
